package com.example.shop

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.CartEntity
import com.example.base.entity.OrderCreateEntity
import com.example.base.mvi.BaseFragment
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.base.param.OrderCreate
import com.example.base.param.OrderDetail
import com.example.shop.databinding.FragmentCartBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding,ShopIntent,ShopViewModel>() {

    var index = -1//修改的下标
    var cartNum = 0//修改的购物车数量

    val cartAdapter by lazy { CartAdapter() }
    override fun getLayout(): Int  = R.layout.fragment_cart

    override fun getVM(): Class<ShopViewModel>  = ShopViewModel::class.java

    override fun initView() {
        binding.rvCart.apply {
            adapter = cartAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
        viewModel.sendIntent(ShopIntent.cart("true",10,1))
        //点击item上的复选框，底部金额及选中状态发生变化
        cartAdapter.addChildClickViewIds(R.id.cart_cb,R.id.cart_add,R.id.cart_sub)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            index = position
            when(view.id){
                R.id.cart_cb->{
                    cartAdapter.data[position].isChecked =!cartAdapter.data[position].isChecked
                }
                R.id.cart_add->{
                    val id = cartAdapter.data[position].id
                    cartNum = cartAdapter.data[position].cartNum+1
                    viewModel.sendIntent(ShopIntent.cartUpdate(id,cartNum))
                }
                R.id.cart_sub->{
                    cartNum = cartAdapter.data[position].cartNum
                    if(cartNum==1){
                        ToastUtils.showLong("不能再减少了")
                        return@setOnItemChildClickListener
                    }
                    cartNum--
                    val id = cartAdapter.data[position].id
                    viewModel.sendIntent(ShopIntent.cartUpdate(id,cartNum))
                }
            }
            checkBottom()
        }

        //底部全选的点击事件
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.cb.setOnClickListener {
                cartAdapter.data.forEach {
                    it.isChecked = isChecked //全选//!it.isChecked//反选
                }
                checkBottom()
                cartAdapter.notifyDataSetChanged()
            }
        }
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left  = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                index = viewHolder.layoutPosition
                viewModel.sendIntent(ShopIntent.cartDelete(mutableListOf(cartAdapter.data[index].id)))
            }
        }).attachToRecyclerView(binding.rvCart)

        //点击立即下单
        binding.btnOrdernow.setOnClickListener {
            //判断是否有选中的
            val filter = cartAdapter.data.filter { it.isChecked }
            if(filter.size>0){
                //有选中的
                //创建参数的实体类 OrderCreate
                val orderCreate = OrderCreate()
                val list = mutableListOf<OrderDetail>()
                filter.forEach {
                    val orderDetail = OrderDetail()
                    orderDetail.productId = it.productId
                    orderDetail.attrValueId = it.attrId
                    orderDetail.productNum = it.cartNum

                    list.add(orderDetail)
                }
                orderCreate.orderDetails = list
                viewModel.sendIntent(ShopIntent.orderCreate(orderCreate))
            }else{
                ToastUtils.showLong("请至少选择一种商品")
            }
        }

    }

    private fun checkBottom() {
        //检查是否全选中 //选中的集合
        val filter = cartAdapter.data.filter { it.isChecked }
        if(filter.size==cartAdapter.data.size && cartAdapter.data.size>0){
            binding.cb.isChecked = true
        }else{
            binding.cb.isChecked = false
        }
        //计算选中的金额
        var amount = 0f
        filter.forEach {
            amount+=it.cartNum*it.price.toFloat()
        }
        binding.tvMoney.text = "合计:￥$amount"

    }

    override fun initData() {
       lifecycleScope.launch {
           viewModel.uiState.collect{
               when(it){

                   is UiState.onSuccess<*> -> {
                       when(it.type){
                           HttpType.DEFAULT -> {
                               val cartEntity = it.data as CartEntity
                               cartAdapter.apply {
                                   data.clear()
                                   data.addAll(cartEntity.list)
                                   notifyDataSetChanged()
                               }
                           }

                           HttpType.UPDATE -> {
                               ToastUtils.showLong("操作成功")
                               //页面上数据发生变化  adapter数据发生变化
                               (cartAdapter.getViewByPosition(index,R.id.cart_num) as TextView).text = cartNum.toString()
                               cartAdapter.data[index].cartNum = cartNum
                           }

                           HttpType.DELETE -> {
                                ToastUtils.showLong("删除成功")
                               cartAdapter.data.removeAt(index)
                               cartAdapter.notifyItemRemoved(index)
                           }
                           HttpType.ADD->{
                               val orderCreateEntity = it.data as OrderCreateEntity
                               ToastUtils.showLong("创建订单成功${orderCreateEntity.orderNo}")
                           }
                           else->{}
                       }
                   }
                   else ->{}
               }
           }
       }
    }

}